<?php

namespace App\Http\Controllers\API;

use App\Repositories\UsersRepository;
use App\User;
use App\ZL\Controllers\ApiBaseController;
use App\ZL\Library\ErrorCode;
use App\ZL\ORG\Xcx\Common;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Str;

class UserCenterController extends ApiBaseController
{
    protected $xcx;
    protected $user;

    protected $appid;
    protected $secret;

    public function __construct(UsersRepository $usersRepository)
    {
        $this->appid = config('xcx.appid');
        $this->secret = config('xcx.secret');


        $this->user = $usersRepository;
        $this->xcx = new Common($this->appid,$this->secret);
    }

//    public function getSessionKey()
//    {
//        return isset($_SERVER['HTTP_AUTHTOKEN'])?$_SERVER['HTTP_AUTHTOKEN']:I('authToken');
//    }

    public function getSessionKey(Request $request)
    {
        $data = json_decode($this->xcx->getSessionKey($request->code),true);
        if(isset($data['session_key'])){
            $session_id = Str::random(40);
            cache([$session_id=>json_encode($data)],isset($data['expires_in'])?$data['expires_in']/60:120);
            $res = [
              'session_id' =>$session_id,
              'openid' =>$data['openid'],
            ];
            $user = User::where('xcx_openid',$data['openid'])->first();
            if(!$user){
                $user = User::create([
                    'xcx_openid'=>$data['openid'],
                ]);
                $res['new'] = 1;
            }else{
                $res['new'] = 0;
            }
            return responseZK(1,$res);
        }else{
            return responseZK(0,[],$data['errmsg']);
        }
    }

    public function setLogin(Request $request)
    {
        $session_key = getSessionData()['session_key'];
        $data = '';
        $errCode = $this->xcx->decryptData($request,$session_key, $data);
        if ($errCode == 0) {
            $user = json_decode($data,true);
            $id = $this->user->checkHasAndSaveInfo($user);
            if($id){
                addSessionData(['id'=>$id,'remember_token'=>$session_key]);

//            $secret = $this->user->saveTokenAndGetSecret($id,$session_key);

                $user = User::find($id);
                return responseZK(1,$user->toArray());
            }else{
                return responseZK(ErrorCode::$modelSaveError['code'],[],ErrorCode::$modelSaveError['msg']);
            }

        } else {
            return responseZK($errCode,[],$this->xcx->codeToStr($errCode));
        }
    }

    public function getAccessToken()
    {
        $access_token = $this->xcx->getAccessToken();
        return responseZK(1,['token'=>$access_token]);
    }
}
